/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.gui.utils;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.peer.ComponentPeer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author tnmkhoi
 */
public class EffectUtils {

  public static void fadeOn(final Container comp, int effectPeriod) {
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleWithFixedDelay(new Runnable() {
      private Integer alpha;
      private Color bgColor = comp.getBackground();
      @Override
      public void run() {
        try {
          //        System.out.println("Component@" + comp.hashCode() + ", alpha: " + alpha);
          if (alpha == null) {
            alpha = bgColor.getAlpha();
          }
          if (alpha == 0) {
            scheduler.shutdown();
          }
          Thread.sleep(40);
          alpha--;
          setWindowAlpha(comp, alpha);
        } catch (Exception ex) {
          Logger.getLogger(EffectUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }, 0, effectPeriod, TimeUnit.MILLISECONDS);
//    Timer t = new Timer(effectPeriod, new ActionListener() {
//      @Override
//      public void actionPerformed(ActionEvent e) {
//        
//      }
//    });
//    t.start();
  }

  public static void setComponentAlpha(Component comp, float alpha) {
    Color bgColor = comp.getBackground();
    comp.setBackground(new Color(
            bgColor.getRed(),
            bgColor.getGreen(),
            bgColor.getBlue(),
            alpha));
  }

  public static void setWindowAlpha(Container w, float alpha) {
    ComponentPeer peer = w.getPeer();
    if (peer == null) {
      return;
    }
    Class< ? extends ComponentPeer> peerClass = peer.getClass();

    //noinspection EmptyCatchBlock
    try {
      Class< ?> nativeClass = Class.forName("apple.awt.CWindow");
      if (nativeClass.isAssignableFrom(peerClass)) {
        Method setAlpha = nativeClass.getMethod(
                "setAlpha", float.class);
        setAlpha.invoke(peer, Math.max(0.0f, Math.min(alpha, 1.0f)));
      }
    } catch (ClassNotFoundException e) {
    } catch (NoSuchMethodException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }
  }
}
